﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace DiverseStudents.Scripts
{
    internal class ListItemDragScript : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IEndDragHandler, IBeginDragHandler
    {
         private int startIndex;
        // private int originalIndex;
        private int sibling;
        private float topPadding;
        private float height;
        private float spacing;
        private float pressStartTime;
        private bool isPressing;
        private bool isDragging;
        private const float pressTimeThreshold = 0.3f; //0.5s
        protected virtual void Update()
        {
            if (isPressing && Time.time - pressStartTime >= pressTimeThreshold)
            {
                isDragging = true;
            }
        }

        protected virtual void OnEnable()
        {
            try
            {
                topPadding = transform.parent.GetComponent<VerticalLayoutGroup>().padding.top;
                spacing = transform.parent.GetComponent<VerticalLayoutGroup>().spacing;
                height = GetComponent<RectTransform>().sizeDelta.y;
            }
            catch (Exception e)
            {
                DLog.Error(e);
            }
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            if (isDragging)
            {
                startIndex = transform.GetSiblingIndex();
                //originalIndex = transform.GetSiblingIndex();
                transform.SetSiblingIndex(transform.parent.childCount - 1);
                GetComponent<LayoutElement>().ignoreLayout = true;
                transform.parent.GetComponent<ListEmpetDragScript>().ShowEmpty();
            }
        }
        public void OnDrag(PointerEventData eventData)
        {
            if (isDragging)
            {
                transform.position = new Vector3(transform.position.x, eventData.position.y, transform.position.z);
               
                sibling = -(int)((transform.localPosition.y - topPadding) / (height + spacing));
                transform.parent.GetComponent<ListEmpetDragScript>().SetEmptyIndex(sibling);
            }
        }
        public void OnEndDrag(PointerEventData eventData)
        {
            if (isDragging)
            {
                transform.parent.GetComponent<ListEmpetDragScript>().HideEmpty();
                transform.SetSiblingIndex(sibling);
                GetComponent<LayoutElement>().ignoreLayout = false;
                isDragging = false;
            }
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            pressStartTime = Time.time;
            isPressing = true;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            isPressing = false;
        }
    }
}
